#include "TreeNode.h"
#include "FTBitmapChar.h"

Allocator<TreeNode> TreeNode::allocator;

TreeNode::TreeNode() {
	this->x         = 0;
	this->y         = 0;
	this->width     = 0;
	this->height    = 0;
	this->leaf1     = NULL;
	this->leaf2     = NULL;
}

TreeNode::TreeNode(int x, int y, int width, int height) {
	this->x = x;
	this->y = y;
	this->width = width;
	this->height = height;
	this->leaf1 = NULL;
	this->leaf2 = NULL;
}

void TreeNode::set(int x, int y, int width, int height) {
	this->x         = x;
	this->y         = y;
	this->width     = width;
	this->height    = height;
	this->leaf1     = NULL;
	this->leaf2     = NULL;
}

TreeNode::~TreeNode()
{
	this->x         = 0;
	this->y         = 0;
	this->width     = 0;
	this->height    = 0;
}

void TreeNode::createBranches(FTBitmapChar *bitmapChar) {
	int dx = width - bitmapChar->getWidth();
	int dy = height - bitmapChar->getHeight();
	// we split to give one very small leaf and one very big one
	// because it allows more efficent use of space
	// if you don't do this, the bottom right corner never gets used
	if (dx < dy) {
		//	split so the top is cut in half and the rest is one big rect below
		leaf1 = allocator.getNew();
		leaf1->set(x + bitmapChar->getWidth(), y, width - bitmapChar->getWidth(), bitmapChar->getHeight());
		leaf2 = allocator.getNew();
		leaf2->set(x, y + bitmapChar->getHeight(), width, height - bitmapChar->getHeight());
	} else {
		//	m_pLeaf1 = left (cut in half)
		leaf1 = allocator.getNew();
		leaf1->set(x, y + bitmapChar->getHeight(), bitmapChar->getWidth(), height - bitmapChar->getHeight());
		// m_pLeaf2 = right (not cut)
		leaf2 = allocator.getNew();
		leaf2->set(x + bitmapChar->getWidth(), y, width - bitmapChar->getWidth(), height);
	}
}

bool TreeNode::add(FTBitmapChar *bitmapChar) {
	if (bitmapChar->isEmpty())
        return true;
	if (isEmpty()) {	
		if (fits(bitmapChar)){
			createBranches(bitmapChar);
			bitmapChar->setXY(x, y);
			return true;
		}
		return false;
	}
	if (leaf1->add(bitmapChar)) {
		return true;
	}
	if (leaf2->add(bitmapChar)) {
		return true;
	}
	return false;		
}

bool TreeNode::fits(FTBitmapChar *bitmapChar) {
	return bitmapChar->getWidth() <= width && bitmapChar->getHeight() <= height;
}

